package com.ww.microrpc.loadbalancer;

import com.netflix.client.ClientException;
import com.netflix.client.RequestSpecificRetryHandler;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.ww.microrpc.client.Client;
import com.ww.microrpc.netty.NettyClient;
import com.ww.microrpc.netty.NettyClientConfig;
import com.ww.microrpc.netty.RequestHolder;
import com.ww.microrpc.netty.protocol.ResponseMessage;

import java.io.IOException;

public class RpcLoadBalancer extends AbstractLoadBalancerAwareClient {

    private Client client;

    public RpcLoadBalancer(ILoadBalancer lb,
                           IClientConfig clientConfig,
                           NettyClientConfig nettyClientConfig) {
        super(lb, clientConfig);
        client = new NettyClient(nettyClientConfig);
    }

    @Override
    public ResponseMessage executeFuture(RequestHolder request) {
        if (request.getUrl() == null) {
            Server server = super.getLoadBalancer().chooseServer(request.getClientName());
            request.setUrl(server.getHost() + ":" + server.getPort());
        }
        try {
            return client.execute(request);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseMessage executeWithLoadBalancer(RequestHolder request) throws ClientException {
        return super.executeWithLoadBalancer(request);
    }


    @Override
    public RequestSpecificRetryHandler getRequestSpecificRetryHandler(RequestHolder request, IClientConfig requestConfig) {
        return null;
    }


}